var checkedNodes = [];
var agin=0;
var seconds=0;
layui.use(['element', 'table', 'form', 'layer', 'upload'], function () {
    var element = layui.element;
    var $ = layui.$;
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var upload = layui.upload;

    //获取创建人id
    var createId = localStorage.getItem('createId');
    $('input[name=createId]').val(createId);


    //上传图片
    var uploadInst = upload.render({
        elem: "#url",
        url: "/courseTable/upFile",
        multiple: true,
        field: "files",
        accept: "images",
        before: function (obj) {
            agin++;
            if(agin>=7){
                layer.alert("最多上传6张图片");
                return;
            }
            $('#images').show();
            obj.preview(function (index, file, result) {
                $('#image').append('<img src="' + result
                    + '" alt="' + file.name
                    + '"height="100px" width="100px" border="1px solid #ccc" class="layui-upload-img uploadImgPreView">');
            });
        },
        done: function (res, index, upload) {
            var mainImage = res.data;
            $('#img').attr('src', mainImage);
            $('input[name=mainImage]').val(mainImage);
        },
        error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }, progress: function (n, elem, e) {
            element.progress('demo', n + '%');
            if(agin>=7){
                return;
            }
            if (n == 100) {
                layer.msg('上传完毕', {icon: 1});
            }
        }
    });

    //上传视频
    var uploadInst = upload.render({
        elem: "#course_url",
        url: "/courseTable/uploadFile",
        multiple: true,
        field: "files",
        accept: "video",
        before: function (obj) {
            obj.preview(function (index, file, result) {
            });
        },
        done: function (res, index, upload) {
            var mainImage = res.data;
            var url='<p style="margin-left: 20px">视频预览:</p><video id="myVideo" src="'+mainImage.path+'"width="200px" height="200px" type="video/mp4" controls autoplay '+'border="1px solid #ccc" style="margin-left: 50px;margin-top:5px;idth: 250px;height: 150px;border-color: #0C0C0C;border-style:solid"></video>'
            $("#video").html(url);
        },
        error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }, progress: function (n, elem, e) {
            element.progress('demo', n + '%');
            if (n == 100) {
                layer.msg('上传完毕', {icon: 1});
            }
        }
    });

    /*课程分类*/
    findType = function findType() {

        layer.open({
            type: 1,
            title: '选择分类',
            area: ['500px', '400px'],
            maxmin: true,
            shade: 0,
            offset: 'auto',
            content: '<ul id="ztree" class="ztree"></ul>',
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                $('#sort').show();
                layer.close(index);
            },
            btn2: function (index, layero) {

            }
        });
        var settingss = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "categroyId",   //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            check: {
                enable: true,
                chkStyle: 'checkbox',
                nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            callback: {
                onCheck: onCheck
            }
        };
        //点击节点
        function onCheck(e, treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj("ztree"),
                nodes = treeObj.getCheckedNodes(true),
                v = "";
            title = "";
            categroyId = "";
            for (var i = 0; i < nodes.length; i++) {
                v += nodes[i].title + ">";
                title = nodes[i].title;
                categroyId = nodes[i].categroyId;
                checkedNodes += nodes[i].categroyId+'';
            }
            var leng = v.substring(v.indexOf('>')+1);
            v = leng.substring(0,leng.length-1)
            $('#type').text(v);
            $('input[name=title]').val(title);
            $('input[name=categroyId]').val(categroyId);
        }
        //加载树的数据
        $.ajax({
            url: "/goodsTree/getTree",
            type: 'post',
            dataType: 'json',
            success: function (data) {
                zTreeObj = $.fn.zTree.init($("#ztree"), settingss, data.data); //初始化树
                zTreeObj.expandAll(true);   //true 节点全部展开、false节点收缩
                // 回显选中的数据
                var treeObj = $.fn.zTree.getZTreeObj("ztree");
                for(var i = 0; i < checkedNodes.length; i++) {
                    var rnode = treeObj.getNodeByParam("categroyId", checkedNodes[i]);
                    treeObj.checkNode(rnode,true);
                }
            }
        });
    }

    //提交
    $('#submit').on('click', function () {

        var i = setInterval(function() {
            var divObj = document.querySelector("#video");
            var time = document.querySelector("#myVideo");
            if(time.readyState > 0) {
                var minutes = parseInt(time.duration / 60, 10);
                var second = time.duration % 60;
                console.log(second);
                localStorage.setItem("second",second);
                // (Put the minutes and seconds in the display)

                clearInterval(i);
            }
        }, 200);
        var paramProduct = $('#form').serialize();
        var seconds=localStorage.getItem("second");
        console.log(seconds);
        paramProduct.createId="1004";
        var num=Math.round(seconds);
        paramProduct+="&courseTime="+num;
        console.log(paramProduct);
        console.log(num);
        $.ajax({
            url: '/courseTable/addCourse',
            type: 'post',
            dataType: 'json',
            async: false,
            data: paramProduct,
            success: function (data) {
                var createId = $('input[name=createId]').val();
                var paramRecord = {
                    'launchId': createId,
                    'result': '2',
                    'type': 3
                }
                $.ajax({
                    url: '/Record/addJsCourseRecord',
                    type: 'post',
                    dataType: 'json',
                    async: false,
                    data: paramRecord,
                    success: function (data) {
                        layer.msg("添加成功");
                    }
                })
            },
            error: function () {

            }
        });
    });

    //下拉框
    getCourseClass();
    function getCourseClass() {
        $.ajax({
            url: '/courseTable/getCourseClass',
            type: 'post',
            dataType: 'json',
            success: function (data) {
                var opt="<select name='classId' id='classId'>";
                opt+="<option value=''>请选择课程分类</option>";
                for(var da in data.data) {
                    var ba=da;
                    da++;
                    opt +="<option value='"+da+ "'>"+data.data[ba].title+"</option>"
                }
                opt+="</select>"
                $("#sot").html(opt);
                //刷新下拉框
                form.render('select');
            }
        });
    }
});

//返回
function goBack() {
    parent.$('#quickHref').val('课程列表');
    parent.getQuick();
    return;
}

// // 视频
// // 定义一个变量：videoObject，用来做为视频初始化配置
// var videoObject = {
//     container: '#video', //“#”代表容器的ID，“.”或“”代表容器的class
//     variable: 'player', //播放函数名称，该属性必需设置，值等于下面的new ckplayer()的对象
//     video: 'http://ckplayer-video.oss-cn-shanghai.aliyuncs.com/sample-mp4/05cacb4e02f9d9e.mp4',//视频地址
//     debug:true//开启调试模式
// };
// var player = new ckplayer(videoObject);//初始化播放器
//
